import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken } from '@/utils/auth'
import Qs from 'qs';

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
});

// 异常状态码
const HTTP_STATUS = {
  '400': '参数错误',
  '401': '未授权',
  '403': '访问被拒绝',
  '404': '请求地址不存在',
  '408': '请求超时',
  '500': '服务器内部错误',
  '501': '服务未实现',
  '502': '网关错误',
  '503': '服务不可用',
  '504': '网关超时'
};

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['X-Requested-With'] = 'XMLHttpRequest';
    // config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    // config.headers['Content-Type'] = 'application/json';
    if (store.getters.token) {
      // ['X-Token'] is a custom headers key
      // config.headers['X-Token'] = getToken()
      config.headers['vue_admin_template_token'] = getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // if the custom code is not 20000, it is judged as an error.
    // return response
    const { code, data, message } = response;
    const res = response.data;
    if (code !== 200) {
      Message({
        type: 'error',
        message: message,
        duration: 5 * 1000
      })
      return Promise.reject(response);
    } else {
      return res
    }
  },
  error => {
    if (error && error.response) {
      return responseErrorHandler(error.response);
    }
  }
)

/**
 * 业务错误处理
 */
function bizErrorHandler(response) {
  const { status } = response;
  if (status === 401) {
    // 跳转登录、清除token
    store.dispatch('user/resetToken').then(() => {
      location.reload()
    })
  } else if (status === 403) {
    // 无权限访问，弹框提示是否跳转至指定页面(一般指首页)
    router.push('/')
  } else {
    Message({
      message: HTTP_STATUS[status],
      type: 'error',
      duration: 5 * 1000
    })
  }

  if (process.env.NODE_ENV === 'development') {
    console.error(
      'URL: %s\n Method: %s\n Params: %s\n Response: %s',
      response.config.url,
      response.config.method,
      JSON.stringify(response.config.data || response.config.params),
      JSON.stringify(response.data)
    );
  }

  return Promise.reject(response);
}

/**
 * 响应错误处理
 */
function responseErrorHandler(response) {
  const { status, data } = response;
  const successed = status >= 200 && status < 300 || status === 304;
  if (data != null) {
    return bizErrorHandler(response);
  } else {
    if (!successed) {
      const error = new Error(HTTP_STATUS[status] || '未知错误');
      error.response = response;
      return Promise.reject(error);
    }
  }

  return response;
}

/**
 * 封装请求方式
 */
const http = {
  post(url, params) {
    return service.post(url, params, {
      transformRequest: [params => JSON.stringify(params)],
      headers: {
        'Content-Type': 'application/json'
      }
    })
  },
  put(url, params) {
    return service.put(url, params, {
      transformRequest: [params => JSON.stringify(params)],
      headers: {
        'Content-Type': 'application/json'
      }
    })
  },
  get(url, params) {
    return service.get(url, {
      params,
      paramsSerializer: params => Qs.stringify(params)
    })
  },
  // restful api
  getRestApi(url, params) {
    let _params;
    if (Object.is(params, null || undefined)) {
      _params = '';
    } else {
      _params = '/';
      for (const key in params) {
        if (Object.prototype.hasOwnProperty.call(params, key) && params[key] !== null && params[key] !== undefined) {
          _params += `${params[key]}/`;
        }
      }
      _params = _params.substr(0, _params.length - 1);
    }
    console.log(_params, '----params')
    if (_params) {
      return service.get(`${url}${_params}`);
    } else {
      return service.get(url);
    }
  },
  deleteApi(url, params) {
    let _params;
    if (Object.is(params, null || undefined)) {
      _params = '';
    } else {
      _params = '/';
      for (const key in params) {
        if (Object.prototype.hasOwnProperty.call(params, key) && params[key] !== null && params[key] !== undefined) {
          _params += `${params[key]}/`;
        }
      }
      _params = _params.substr(0, _params.length - 1);
    }
    console.log(_params, '----params')
    if (_params) {
      return service.delete(`${url}${_params}`).catch(error => {
        Message({
          message: error.message,
          type: 'error',
          duration: 5 * 1000
        });
        return Promise.reject(error);
      });
    } else {
      return service.delete(url).catch(error => {
        Message({
          message: error.message,
          type: 'error',
          duration: 5 * 1000
        });
        return Promise.reject(error);
      });
    }
  },
  // 文件上传
  upload(url, params) {
    return service.post(url, params, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  // 请求登录
  login(url, params) {
    return service.post(url, params, {
      transformRequest: [params => Qs.stringify(params)],
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
        // 'Content-Type': 'application/json'
      }
    })
  }
}

export default http
